package com.joizhang.seckill.controller;

import com.joizhang.seckill.api.redis.UserKey;
import com.joizhang.seckill.api.service.DemoService;
import com.joizhang.seckill.api.vo.UserVo;
import com.joizhang.seckill.limit.ApiRateLimiter;
import com.joizhang.seckill.limit.LimitType;
import com.joizhang.seckill.utils.Result;
import com.joizhang.seckill.utils.WebCodeMsg;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/demo")
public class DemoController {

    @DubboReference
    private DemoService demoService;

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World";
    }

    @ApiRateLimiter(qps = 1, limitType = LimitType.METHOD)
    @RequestMapping("/hello1")
    @ResponseBody
    public Result<String> hello1() {
        return Result.success("Hello, World!");
    }

    @ApiRateLimiter(qps = 1, limitType = LimitType.IP)
    @RequestMapping("/hello2")
    @ResponseBody
    public Result<String> hello2() {
        return Result.success("Hello, Java!");
    }

    @RequestMapping("/error")
    @ResponseBody
    public Result<String> error() {
        return Result.error(WebCodeMsg.SERVER_ERROR);
    }

    @RequestMapping("/Thymeleaf")
    public String thymeleaf(Model model) {
        model.addAttribute("name", "Jesper");
        return "hello";
    }

    @RequestMapping("/redis/set")
    @ResponseBody
    public Result<Boolean> redisSet() {
        UserVo user = new UserVo();
        user.setId(0L);
        user.setUsername("Joseph");
        Boolean b1 = demoService.setRedis(UserKey.USER_ID, String.valueOf(user.getId()), user);
        return Result.success(b1);
    }

    @RequestMapping("/redis/get")
    @ResponseBody
    public Result<UserVo> redisGet() {
        UserVo user = demoService.getRedis(UserKey.USER_ID, String.valueOf(0L), UserVo.class);
        return Result.success(user);
    }

    @RequestMapping("/redis/init")
    @ResponseBody
    public Result<Boolean> redisInit() {
        Boolean result = demoService.initRedis();
        return Result.success(result);
    }

    @RequestMapping("/db/doubleInsert")
    @ResponseBody
    public Result<Boolean> doubleInsert() {
        try {
            demoService.doubleInsert();
            return Result.success(true);
        } catch (Exception e) {
            return Result.error(WebCodeMsg.PRIMARY_ERROR);
        }
    }

    @RequestMapping("/db/get")
    @ResponseBody
    public Result<UserVo> dbGet() {
        UserVo user = demoService.getUserById(1L);
        return Result.success(user);
    }

    @RequestMapping("/mq")
    @ResponseBody
    public Result<String> mq() {
        demoService.sendToMQ("hello, imooc");
        return Result.success("Hello, world!");
    }

}
